package cn.edu.zjut.mina.service.impl;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.Properties;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.edu.zjut.mina.bean.MyAppInfo;
import cn.edu.zjut.mina.bean.StandardFormat;
import cn.edu.zjut.mina.po.UserInfo;
import cn.edu.zjut.mina.repository.UserInfoRepository;
import cn.edu.zjut.mina.service.ILoginService;
import cn.edu.zjut.mina.util.DateUtils;
import cn.edu.zjut.mina.util.GsonUtils;
import cn.edu.zjut.mina.util.HttpUtils;

@Service("loginService")
public class LoginServiceImpl implements ILoginService {
	
	@Autowired
	private UserInfoRepository userInfoRepository;
	private Random random = new Random(System.currentTimeMillis());
	/**
	 * 第一次登入,根据code获取用户信息,保存并返回
	 * @param code 用户code
	 * @return 用户信息
	 */
	@Transactional(rollbackFor=Exception.class)
	public String firstLogin(String code) {
		String datas = "";
		StandardFormat outJson = new StandardFormat();
		String url = MyAppInfo.getAccess_tokenUrl(code);
		String result = HttpUtils.sendGet(url);
		if (result != null) {
            try {
            	JSONObject jsonObj = JSONObject.fromObject(result);
            	System.out.println(result);
                final String unionid = jsonObj.getString("unionid");
                final String openid = jsonObj.getString("openid");
                final String refresh_token = jsonObj.getString("refresh_token");
                final String expires_in = jsonObj.getString("expires_in");
                final String access_token = jsonObj.getString("access_token");
                url = MyAppInfo.getUserInfoUrl(access_token, openid);
                
                result = HttpUtils.sendGet(url);
                if (result != null) {
                    try {
                    	JSONObject jsonObj2 = JSONObject.fromObject(result);
                    	String nickname = jsonObj2.getString("nickname");
                        String sex = jsonObj2.getString("sex");
                        String province = jsonObj2.getString("province");
                        String city = jsonObj2.getString("city");
                        String country = jsonObj2.getString("country");
                        String headimgurl = jsonObj2.getString("headimgurl");
                        
                        UserInfo user = null;
                        if (userInfoRepository.findByOpenid(openid) == null) {//保存操作
                        	user = new UserInfo();
                        	user.setRoomCardNum(10);//初始房卡为10
                        } else {//更新操作   更新 = 查找 + 修改 + 保存
                        	user = userInfoRepository.findByOpenid(openid);
                        }
                        
                        /**
                         * 数据库操作
                         * 保存用户信息
                         */
                        user.setUnionid(unionid);
                        user.setOpenid(openid);
                        user.setRefresh_token(refresh_token);
                        user.setExpires_in(expires_in);
                        user.setAccess_token(access_token);
                        user.setNickName(nickname);
                        user.setSex(sex);
                        user.setProvince(province);
                        user.setCity(city);
                        user.setCountry(country);
                        user.setHeadimgurl(headimgurl);
                        user.setRefresh_token_time(new Date());
                        user.setAccess_token_time(new Date());
                        userInfoRepository.saveAndFlush(user);
                        
                        String userid = "";
                        //生成userid
                        user = userInfoRepository.findByOpenid(openid);
                        if (user.getUserId() == null || user.getUserId().equals("")) {
                        	int autoid = user.getAutoid();
                            /**
                             * 以下操作基于用户数量小于等于6位来做
                             */
                            userid = String.valueOf((random.nextInt(89) + 10) * 1000000  + autoid);
                            
                            user.setUserId(userid);
                            userInfoRepository.saveAndFlush(user);
                        } else {
                        	userid = user.getUserId();
                        }
                        
                        
                        
                        
                        outJson.nickname = nickname;
                        outJson.sex = sex;
                        outJson.province = province;
                        outJson.city = city;
                        outJson.country = country;
                        outJson.headimgurl = headimgurl;
                        outJson.openid = openid;
                        outJson.userId = userid;
                        outJson.roomcardnum = user.getRoomCardNum();
                        outJson.type = 1;//登入成功
                        //datas = GsonUtils.beanToJson(outJson).trim();
                    } catch (Exception e) {
                    	System.out.println("解析请求2出现异常！" + e);
                    	outJson.type = 2;//登入失败
                    	outJson.resultInfo = "firstLogin:解析请求2出现异常！";
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {
            	System.out.println("解析请求1出现异常！" + e);
            	outJson.type = 2;//登入失败
            	outJson.resultInfo = "firstLogin:解析请求1出现异常！";
                e.printStackTrace();
            }
        }
		datas = GsonUtils.beanToJson(outJson).trim();
		return datas;
	}

	@Transactional(rollbackFor=Exception.class)
	public String secondLogin(String openid) {
		// TODO Auto-generated method stub
		String datas = "";
		StandardFormat outJson = new StandardFormat();
		
		if (userInfoRepository.findByOpenid(openid) == null) {// openid不存在
			outJson.type = 2;// 登入失败
			outJson.resultInfo = "openid不存在";
			System.out.println("openid不存在");
		} else {
			String url = "";
			UserInfo user = userInfoRepository.findByOpenid(openid);
			Date access_token_time = user.getAccess_token_time();//2小时过期
			int seconds = DateUtils.getSeconds(access_token_time, new Date());
			if (seconds < Integer.parseInt(user.getExpires_in()) - 60) {// access_token未过期，60应该改成120
				url = MyAppInfo.getUserInfoUrl(user.getAccess_token(), openid);
				String result = HttpUtils.sendGet(url);
				System.out.println("GET请求返回结果：" + result);
				if (result != null) {
					try {
						JSONObject jsonObj = JSONObject.fromObject(result);
						String nickname = jsonObj.getString("nickname");
                        String sex = jsonObj.getString("sex");
                        String province = jsonObj.getString("province");
                        String city = jsonObj.getString("city");
                        String country = jsonObj.getString("country");
                        String headimgurl = jsonObj.getString("headimgurl");
                        
                        user.setNickName(nickname);
                        user.setSex(sex);
                        user.setProvince(province);
                        user.setCity(city);
                        user.setCountry(country);
                        user.setHeadimgurl(headimgurl);
                        userInfoRepository.saveAndFlush(user);
                        
						outJson.nickname = nickname;
                        outJson.sex = sex;
                        outJson.province = province;
                        outJson.city = city;
                        outJson.country = country;
                        outJson.headimgurl = headimgurl;
                        outJson.openid = openid;
                        outJson.userId = user.getUserId();
                        outJson.roomcardnum = user.getRoomCardNum();
                        outJson.type = 1;//登入成功
					} catch (Exception e) {
						System.out.println("解析异常111");
						System.out.println("解析请求出现异常！" + e.getMessage());
						outJson.type = 2;// 登入失败
						outJson.resultInfo = "secondLogin:解析请求出现异常！"+e.getMessage();
						e.printStackTrace();
					}
			    }
			} else if (DateUtils.getDays(user.getRefresh_token_time(),
					new Date()) <= 29) {// refresh_token未过期

				url = MyAppInfo.getRefreshAccess_tokenUrl(user.getRefresh_token());
				System.out.println("输出refresh_token"+openid);
				System.out.println(user.getRefresh_token());
				String result = HttpUtils.sendGet(url);
				System.out.println(result);
				if (result != null) {
					try {
						JSONObject jsonObj = JSONObject.fromObject(result);
						String access_token = jsonObj.getString("access_token");
						
						user.setAccess_token(access_token);
						user.setAccess_token_time(new Date());
						
						url = MyAppInfo.getUserInfoUrl(access_token, openid);
						result = HttpUtils.sendGet(url);
						if (result != null) {
							try {
								jsonObj = JSONObject.fromObject(result);
								String nickname = jsonObj.getString("nickname");
								String sex = jsonObj.getString("sex");
		                        String province = jsonObj.getString("province");
		                        String city = jsonObj.getString("city");
		                        String country = jsonObj.getString("country");
		                        String headimgurl = jsonObj.getString("headimgurl");
		                        
		                        user.setNickName(nickname);
		                        user.setSex(sex);
		                        user.setProvince(province);
		                        user.setCity(city);
		                        user.setCountry(country);
		                        user.setHeadimgurl(headimgurl);
		                        userInfoRepository.saveAndFlush(user);
		                        
								outJson.nickname = nickname;
		                        outJson.sex = sex;
		                        outJson.province = province;
		                        outJson.city = city;
		                        outJson.country = country;
		                        outJson.headimgurl = headimgurl;
		                        outJson.openid = openid;
		                        outJson.userId = user.getUserId();
		                        outJson.roomcardnum = user.getRoomCardNum();
		                        outJson.type = 1;//登入成功
							} catch (Exception e) {
								System.out.println("解析请求2出现异常！" + e);
								outJson.type = 2;// 登入失败
								outJson.resultInfo = "secondLogin:解析请求2出现异常！"+e.getMessage();
								e.printStackTrace();
							}
					    }
						
					} catch (Exception e) {
						System.out.println("解析异常222");
						System.out.println("解析请求1出现异常！" + e);
						outJson.type = 2;// 登入失败
						outJson.resultInfo = "secondLogin:解析请求1出现异常！"+e.getMessage();
						e.printStackTrace();
					}
			    }
				
			} else {// refresh_token过期,另外处理111
				outJson.type = 2;// 登入失败
				outJson.resultInfo = "secondLogin:！refresh_token过期";
			}
		}
			
		datas = GsonUtils.beanToJson(outJson).trim();
		return datas;
	}
	
	
}
